#ifndef KANG_SOCKET_H_
#define KANG_SOCKET_H_
#pragma once

#include "stdafx.h"

class IoServicePool{
public:
	static bool shouldJoin;
	IoServicePool(std::size_t threadsize):next_io_service_(0){
		if (threadsize == 0)
			throw std::runtime_error("io_service_pool size is 0");

		// Give all the io_services work to do so that their run() functions will not
		// exit until they are explicitly stopped.
		for (std::size_t i = 0; i < threadsize; ++i)
		{
			io_service_ptr io_service(new io_service);
			work_ptr work(new io_service::work(*io_service));
			io_services_.push_back(io_service);
			work_.push_back(work);
		}
	}
	IoService& getService(){
		// Use a round-robin scheme to choose the next io_service to use.
		io_service& io_service = *io_services_[next_io_service_];
		++next_io_service_;
		if (next_io_service_ == io_services_.size())
			next_io_service_ = 0;
		return io_service;
	}
	void run(){
		// Create a pool of threads to run all of the io_services.
		std::vector<boost::shared_ptr<boost::thread> > threads;
		for (std::size_t i = 0; i < io_services_.size(); ++i)
		{
			boost::shared_ptr<boost::thread> thread(new boost::thread(
				boost::bind(&io_service::run, io_services_[i])));
			threads.push_back(thread);
		}
		if(shouldJoin){
			// Wait for all threads in the pool to exit.
			for (std::size_t i = 0; i < threads.size(); ++i)
				threads[i]->join();
		}
	}
	void stop()
	{
		// Explicitly stop all io_services.
		for (std::size_t i = 0; i < io_services_.size(); ++i)
			io_services_[i]->stop();
	}
	typedef boost::shared_ptr<io_service> io_service_ptr;
	typedef boost::shared_ptr<io_service::work> work_ptr;

	/// The pool of io_services.
	std::vector<io_service_ptr> io_services_;

	/// The work that keeps the io_services running.
	std::vector<work_ptr> work_;

	/// The next io_service to use for a connection.
	std::size_t next_io_service_;
};
//bool IoServicePool::shouldJoin = true;

class SocketServer
{
public:
	SocketServer(int port,int threadsize=4);
	void run(){
		start();
		iosev_pool_.run();
	}
private:
	IoServicePool iosev_pool_;
	Acceptor acceptor_;
	void start();
	void on_client_accept(Socket *socket,const ErrorCode& ec);
};

#endif